var token;
var u_id;
var num;
var c_id;
var key

var examList_size;
var examId;
var examStatus;
var examStartTime
var q_list_num;

var wsUrl = "ws://localhost:7023"

//接收多值的js函数
function manyValues() {
    var url = window.location.search;
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        key = [token, u_id, num, c_id];
        var value = new Array(strs.length);
        for (i = 0; i < strs.length; i++) {
            value[i] = unescape(strs[i].split("=")[1]);
            key[i] = value[i];
        }
    }
}

//接收Login.html传过来的值
manyValues();
token = key[0];
u_id = key[1];
num = key[2];
c_id = key[3];
listNoStartExams()

//与服务器建立ws连接
wsLogin();

function wsLogin() {
    var ws = new WebSocket(wsUrl + "/server/studentLoginServer/" + num);

    ws.onopen = function (evt) {
        // window.alert("成功与服务端建立websocket连接...")
    }

    //接受消息
    ws.onmessage = function (evt) {
        window.alert(evt.data);
        autoFinish(q_list_num);
        //接收到开始考试的信息后刷新页面，重新加载开始信息
        window.location.reload();
    }

    //断开连接
    ws.onclose = function () {
        $("#username").html("<h3 style=\"text-align: center;\">用户：" + username + "<span>-离线</span></h3>");
    }

}

//查询考试情况
function listNoStartExams() {
    $.ajax({
        headers: {
            'Authorization': token,
        },
        contentType: 'application/x-www-form-urlencoded',
        type: "POST",
        url: "/api/examination/listExamByClazzId",
        data: {
            "clazzId": c_id,
        },
        async: false,
        success: function (result) {
            var txt = "";
            var list = result.data;
            examList_size = list.length;
            for (var i = 0; i < list.length; i++) {
                var txt2 = '<div style="background: aquamarine;width: 500px">\n' +
                    '    <p id="examId" style="display: none">' + list[i].examId + '</p>\n' +
                    '    <span class="status" style="display: none">' + list[i].status + '</span>\n' +
                    '    <p id="bankId" style="display: none">' + list[i].bankId + '</p>\n' +
                    '    <p id="examName">考试名称：' + list[i].examName + '</p>\n' +
                    '    <p class="startTime">预计开始时间：' + list[i].startTime + '</p>\n' +
                    '    <p id="endTime">预计结束时间：' + list[i].endTime + '</p>\n' +
                    '    <p id="statusName">考试状态：' + list[i].statusName + '</p>\n' +
                    '    <span>注意：实际考试时间请以通知为准!</span>\n' +
                    '    <span class="examStartTime">' + list[i].startTime + '</span>\n' +
                    '    <p ><button class="btn-do" value=' + list[i].examId + '>进入考试</button></p>\n' +
                    '</div>'
                txt += txt2;
            }
            $("#div-examList").html(txt);
        }
    });
}

//考试状态操作判断
function examStatusJudge() {
    //未开始和已结束不能进入考试
    if (examStatus == 0 || examStatus == 1 || examStatus == 3) {
        alert("当前不能提交答案！");
        return;
    }

    //准备中
    if (examStatus == 1)
        var timestamp = Date.parse(new Date());
}

//提交答案
function finish(q_num) {
    $("#btn-finish").click(function () {
        examStatusJudge();
        var answerList = [];
        for (var i = 0; i < q_num; i++) {
            answerList.push($($(".stu-answer")[i]).val().toString());
        }
        console.log(answerList)
        console.log(answerList.toString())
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            headers: {
                'Authorization': token,
            },
            type: "POST",
            url: "/api/examination/finish",
            data: JSON.stringify({
                "answerList": answerList,
                "examId": examId,
            }),
            async: false,
            success: function (result) {
                if (result.success) {
                    alert("答案已提交!");
                } else {
                    alert(result.message)
                }
            }
        });
    });
}

//自动提交答案
function autoFinish(q_num) {
    let answerList = [];
    for (var i = 0; i < q_num; i++) {
        answerList.push($($(".stu-answer")[i]).val().toString());
    }
    if (answerList.length == 0) {
        alert("您还没有作答，自动提交答案失败！")
        return;
    }
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        headers: {
            'Authorization': token,
        },
        type: "POST",
        url: "/api/examination/finish",
        data: JSON.stringify({
            "answerList": answerList,
            "examId": examId,
        }),
        async: false,
        success: function (result) {
            if (result.success) {
                alert("答案已提交!");
            } else {
                alert(result.message)
            }
        }
    });
}

beginExam();

//进入考试
function beginExam() {
    for (let i = 0; i < examList_size; i++) {
        $($(".btn-do")[i]).click(function () {
            //考试开始时间
            examStartTime = $($(".examStartTime")[i]).html();

            examStatus = $($(".status")[i]).html();
            console.log("该考试状态：" + $($(".status")[i]).html())
            if ($($(".status")[i]).html() == 0) {
                alert("该考试尚未开始!");
                return;
            }
            if ($($(".status")[i]).html() == 3) {
                alert("该考试已经结束!");
                return;
            }
            examId = $(".btn-do")[i].value;

            $.ajax({
                headers: {
                    'Authorization': token,
                },
                type: "POST",
                url: "/api/examination/listQuestionByExamId?examId=" + examId,
                async: false,
                success: function (result) {
                    var txt = "";
                    var list = result.data;
                    q_list_num = list.length;
                    for (var i = 0; i < list.length; i++) {
                        var txt2 = '<div>\n' +
                            '        <p class="id" style="display: none">' + list[i].id + '</p>\n' +
                            '        <p class="question">题目：' + list[i].question + '</p>\n' +
                            '        <p>\n' +
                            '            答案：<input type="text" class="stu-answer">\n' +
                            '        </p>\n' +
                            '    </div>';
                        txt += txt2;
                    }
                    txt = txt + '<button id="btn-finish">提交答案<button>';
                    $("#div-daExam").html(txt);
                    queryAnswer(examId);

                    //提交答案
                    finish(list.length);
                }
            });
        });
    }
}

//查询答案
function queryAnswer(examId) {
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        headers: {
            'Authorization': token,
        },
        type: "POST",
        url: "/api/examination/queryAnswer",
        data: JSON.stringify({
            "studentId": u_id,
            "examId": examId,
        }),
        async: false,
        success: function (result) {
            if (result.success) {
                for (var i = 0; i < result.data.length; i++) {
                    $($(".stu-answer")[i]).val(result.data[i])
                }
            } else {
                alert(result.message)
            }
        }
    });
}


